System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

35% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Google Ads
Image

Here is a step-by-step design for a simplified version of Google Ads.

1. Problem Definition and Scope

We are designing a large-scale real-time advertising platform. When a user performs a search (e.g., "buy running shoes"), the system runs an auction to select and display relevant text ads alongside organic results. The system must track clicks and strictly enforce advertiser budgets.

Main User Groups

  • Advertisers: Create campaigns, set daily budgets, and bid on keywords.
  • Search Users: Perform searches and view/click ads.

Scope

  • In Scope: Campaign management, Real-time Ad Serving (The Auction), Click Tracking, and Budget Enforcement.
  • Out of Scope: Display/Video ads, complex payment processing (credit card/invoicing), and offline fraud detection pipelines.
Image

2. Clarify functional requirements

  • Must Have:
    • Advertisers can create accounts, campaigns, and ads.
    • Advertisers can set a daily budget and a maximum bid per click.
    • System selects the best ad for a user in real-time (< 200ms) based on bid and relevance.
    • System tracks impressions (views) and clicks reliably.
    • System deducts cost from the advertiser’s budget when a click occurs.
    • Ads stop showing when the daily budget is exhausted.
  • Nice to Have:
    • Detailed analytics dashboard for advertisers.
    • Advanced audience targeting (age, location, interests).
Image

3. Clarify non-functional requirements

  • Scale: Massive. Let’s assume global scale.
  • Traffic:
    • Ad Serving (Reads): Extremely read-heavy. 1 Billion Daily Active Users (DAU).
    • Tracking (Writes): Write-heavy. Millions of clicks per second globally.
  • Latency: Critical. Ad selection must happen within 200ms to avoid slowing down the host page.
  • Availability: High (99.99%). If ads don’t load, we lose revenue directly.
  • Consistency:
    • Ad Creation: Eventual consistency is fine (ads can take a few minutes to go live).
    • Budgeting: We need “near-strong” consistency. We cannot strictly lock rows for every click (too slow), but we must not significantly overspend an advertiser’s budget.
  • Data Retention: Raw event logs kept for a few months; aggregated stats kept for years.
Image

4. Back of the envelope estimates

  • Traffic Estimation:
    • 1 Billion DAU.
    • Average 20 ad impressions per user/day = 20 Billion impressions/day.
    • QPS (Queries Per Second): 20B / 86,400 seconds ≈ 230,000 QPS.
    • Peak traffic is usually 2-3x average, so we design for ~600,000 QPS.
  • Click Traffic:
    • Assume 1% Click-Through Rate (CTR).
    • 20B impressions * 0.01 = 200 Million clicks/day.
    • ~2,300 clicks per second average.
  • Storage:
    • Ad metadata is small (text, URLs). 1M active ads * 10KB = 10GB (fits in memory easily).
    • Click logs are large. 200M clicks * 1KB log size = 200GB/day. We need big data storage for logs.
Image

5. API design

We will use a REST API.

1. Advertiser Management (Ad Service)

  • POST /v1/campaigns
    • Request: { advertiser_id, budget_daily, start_date, end_date }
    • Response: { campaign_id, status: “active” }
  • POST /v1/ads
    • Request: { campaign_id, title, text, image_url, target_url, bid_amount, keywords[] }
    • Response: { ad_id, status: “pending_review” }

2. Ad Serving (Auction Service)

  • GET /v1/ads/allocation
    • Request: { user_id, context_keywords[], location, device_type, count=3 }
    • Response: [ { ad_id, image_url, tracking_url, title } ]
    • Note: This is called by the publisher’s website or app.

3. Event Tracking

  • GET /v1/click (Usually a redirect)
    • Request: { ad_id, campaign_id, user_id, timestamp, signature }
    • Response: HTTP 302 Redirect to target_url.

6. High level architecture

  • Ad Management API: Where advertisers create ads. Writes to SQL DB.

  • Ad Server (Auction): High-performance service that selects ads. Reads from a fast Ad Index (Search/Cache).

  • Event Tracker: Receives clicks/impressions. Does minimal work and pushes events to Kafka to ensure low latency.

  • Stream Processor (Flink/Spark): Consumes Kafka. Aggregates clicks for billing and analytics in real-time.

  • Budget Service: Manages remaining budget. Tells the Ad Server which campaigns are out of money.

Image

7. Data model

We need a mix of SQL for structured data and NoSQL/OLAP for events.

1. Relational DB (PostgreSQL/MySQL)

  • Advertisers Table: id, name, billing_info
  • Campaigns Table: id, advertiser_id, daily_budget, status
  • Ads Table: id, campaign_id, keywords, bid_price, creative_url, status
    • Why SQL? We need ACID compliance for account data and ad configurations.

2. Analytics DB (ClickHouse or Cassandra)

  • Clicks Table: event_id, ad_id, user_id, timestamp, cost, ip_address
  • DailyStats Table: date, campaign_id, total_spend, total_clicks
    • Why NoSQL? Massive write volume and aggregation queries.

8. Core Flows

To understand how the system works at scale, we must separate the User Experience (which must be instant) from the Financial Accounting (which must be accurate). We will trace the three critical lifecycles: Serving the ad, Tracking the money, and Indexing the data.

Flow 1: Ad Serving (The Auction)

Goal: Filter 50 million ads down to the best 3 ads in under 200 milliseconds. Challenge: We cannot query the central SQL database or the central Redis Budget Store for every search. Doing so would create a "Thundering Herd" and crash the database. We must rely on in-memory operations.

This flow follows a Funnel Architecture: we start with millions of candidates and progressively filter them down using increasingly expensive operations on fewer items.

  1. Orchestration (The Ad Mixer)
  • Trigger: A user searches for "cheap home insurance." The Search Engine backend sends a request to the Ad Mixer.
  • Context: The request includes query, user_ip (for location), and device_type.
  • Role: The Mixer is the coordinator. It does not store data itself; it orchestrates calls to the backend shards.
  1. Scatter-Gather Retrieval (The Broad Net)
  • The Problem: The ad inventory is too large to fit on one machine. We use Document Sharding, spreading ads randomly across RAM-based nodes.
  • Scatter: The Mixer fans out the request to all Ad Retrieval Nodes in parallel.
  • Local Lookup: Each node checks its internal Inverted Index. It finds all ads matching "cheap" AND "insurance".
  • Result: Each node returns a list of matching Ad IDs. The Mixer "gathers" these results (e.g., ~1,000 total candidates).
  1. The "Fast" Filter (Budget & Targeting)
  • Before running expensive Machine Learning models, the Mixer must instantly discard invalid ads.

  • Budget Check: The Mixer checks a Local Budget Cache (specifically a "Negative Cache" or list of exhausted campaigns).

  • Optimization: We assume all ads have budget unless we have been notified otherwise. This eliminates network calls to Redis.

  • Targeting: It filters out ads that don't match the user context (e.g., user is on Android, but ad targets iOS).

  1. Ranking (The Auction Logic)
  • We are left with ~200 valid candidates. The Mixer sends them to the Ranking Service.

  • CTR Prediction: The service runs a Deep Learning model to predict the pCTR (Probability of Click-Through) for this specific user.

  • Scoring: It calculates the final score:

  • Why? This ensures we show ads that are relevant (high pCTR), not just the ones with the highest bids (spam).

  • Selection: The top 3 ads are selected.

  1. Response & Signing
  • URL Signing: The Mixer generates a unique tracking_url for the winners.
  • Security: It cryptographically signs the URL parameters (Ad ID, Bid Price) with an HMAC secret.
  • Why? This prevents malicious users from tampering with the URL to change the price or charge the wrong advertiser.
Image

Flow 2: Click Tracking & Billing (The Money Path)

Goal: Record the click, charge the advertiser, and redirect the user. Challenge: We must never block the user's navigation to the landing page while waiting for database writes.

We split this into a Synchronous Path (User Facing) and an Asynchronous Path (Billing).

  1. The Click (User Action)
  • The user clicks the ad. The browser sends a GET request to our Click Handler.
  1. Validation & Redirect (Fast Path)
  • Security: The Handler validates the HMAC signature created in Flow 1. If invalid, the request is rejected (prevents click fraud).
  • Redirect: The Handler immediately returns a HTTP 302 Found to the advertiser’s landing page (e.g., geico.com).
  • Note: We do not charge the credit card or write to SQL yet. Speed is the priority here.
  1. Async Logging (Durability)
  • The Handler produces a ClickEvent to a Kafka topic.
  • Payload: {ad_id, campaign_id, cost, timestamp, impression_id}.
  • Why Kafka? It acts as a buffer. Even if the Billing Database is down, clicks are safely queued and never lost.
  1. Billing Processing (The Consumer)
  • The Budget Service consumes the event from Kafka.
  • Idempotency Check: It checks if this impression_id was already processed to ensure we don't charge twice for an accidental double-click.
  • State Update:
  • Decrements remaining_budget in Redis (Real-time view).
  • Inserts a record into SQL (Permanent ledger for invoicing).
Image

Flow 3: The Feedback Loop (Budget Enforcement)

Goal: Stop serving ads when the budget runs out.

How does the Ad Mixer (Flow 1) know that the Budget Service (Flow 2) just emptied a campaign's wallet?

  1. Exhaustion Detection: When the Budget Service updates Redis and sees the budget hit $0, it publishes a BudgetExhausted event to a Pub/Sub topic (e.g., "control-plane").

  2. Broadcasting: This event is broadcast to all Ad Mixer nodes.

  3. Local Update: The Ad Mixers receive the event and add that Campaign ID to their local Negative Cache.

  4. Result: The next time a user searches, the Ad Mixer sees the campaign in its local cache and drops the ads immediately (Flow 1, Step 3).

  5. Trade-off: There is a slight delay (seconds) between the budget running out and the ads stopping. This means we might "over-deliver" a few clicks (giving them for free), but this is an acceptable cost to keep the Search system fast and available.

Image

Flow 4: Ad Indexing (The Cold Path)

Goal: Make a newly created ad searchable.

  1. Creation: Advertiser submits a new ad via the API. Data is written to the primary SQL Database.

  2. Change Capture: An Indexer Service detects the new row (via SQL polling or CDC).

  3. Flattening: The service "flattens" the relational data (Ad + Campaign + Keywords) into a single search document.

  4. Broadcast: The document is pushed to the Ad Retrieval Nodes, which update their in-memory indexes. The ad is now live.

Image

9. Caching and read performance

The Ad Selection flow must be incredibly fast. We cannot query the main SQL DB for every search.

  • Ad Index (In-Memory): We maintain a specialized inverted index (Keyword -> List of Ads) in memory on the Ad Servers or a dedicated search cluster (like Elasticsearch, but highly optimized).
  • Budget Cache: The Ad Server keeps a local cache of “Active Campaign IDs”. It doesn’t check the exact dollar amount every time; it just checks “Is this ID in the valid set?”.
  • Update Propagation: When an advertiser changes a bid, we write to SQL. A CDC (Change Data Capture) process pushes this update to the Ad Index within seconds.

10. Storage, indexing and media

  • Media Storage: Ad images and banners are stored in Object Storage (S3).
  • CDN: We serve all creative assets (images) via a CDN (Content Delivery Network) so they load instantly for users worldwide.
  • Indexing: The Ads table in SQL is indexed by AdvertiserID for the dashboard. The Ad Index for serving is indexed by Keywords and Targeting Criteria (Location, Device).

11. Scaling strategies

  • Sharding the Ad Index: We have millions of ads. We cannot fit them all on one server. We shard the Ad Index.
    • Strategy: Sharding by Ad ID (Document Partitioning).
    • Query: When a query comes in (”running shoes”), the Aggregator sends the request to all shards. Each shard returns its best matches for “running shoes”. The Aggregator merges the results and sorts by Score.
  • Budget Handling (The “Pacing” Problem):
    • If a campaign has 100.
    • Solution: The Budget Service allocates small “slices” of the budget to different regions or servers. For example, it gives $10 to the US-East cluster. When US-East runs low, it requests another slice. This prevents overspending while maintaining speed.

12. Reliability, failure handling and backpressure

  • Idempotency: Clicks can be accidental double-clicks. The Billing Service must check event_id to ensure we don’t charge the advertiser twice for the same click event.
  • Graceful Degradation: If the sophisticated ML Ranking Service is down or slow, we fall back to a simple ranking (just Bid Price) to ensure ads still show.
  • Data Safety: Billing data is money. We use persistent queues (Kafka) with replication so we never lose a click event even if a server crashes.

13. Security, privacy and abuse

  • Click Fraud: Competitors might write bots to click ads and drain budgets.
    • Mitigation: We analyze IP addresses, click patterns, and user cookies. If a click looks suspicious (e.g., 100 clicks from same IP in 1 second), we mark it as “invalid” and do not charge the advertiser.
  • Privacy: We must anonymize user logs. We should not store PII (Personally Identifiable Information) directly in the raw click logs used for analytics.
  • Encryption: All ad traffic is HTTPS.

14. Bottlenecks and next steps

  • Bottleneck: The “Fan-out” query to ad index shards. As inventory grows, querying all shards becomes expensive.
    • Next Step: Use tiered caching. Cache the “top 100 ads for ‘shoes’” so we don’t query shards for common keywords.
  • Bottleneck: Exact budget enforcement. There is a trade-off between strict budget caps and latency.
    • Next Step: Implement “Probabilistic Throttling”. As budget gets close to 0, artificially lower the bid or skip the auction randomly to smooth out the final spend.

Summary

  • We separated Ad Serving (Read heavy, latency sensitive) from Billing (Write heavy, critical accuracy).
  • We used an Inverted Index for fast keyword matching.
  • We used Kafka to buffer high-speed click events.
  • We handled budget synchronization using Budget Slices to allow distributed servers to serve ads without locking a central database.
Design Amazon S3
Design Amazon Shopping Cart
Mark as Completed

On this page

1. Problem Definition and Scope

Main User Groups

Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

  1. Core Flows

Flow 1: Ad Serving (The Auction)

Flow 2: Click Tracking & Billing (The Money Path)

Flow 3: The Feedback Loop (Budget Enforcement)

Flow 4: Ad Indexing (The Cold Path)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary